package Options::OrderSync::API::ExtractOrderDetails;

use strict;
use warnings;
use DE_EPAGES::Core::API::Error qw (Error );
use DE_EPAGES::Trigger::API::Trigger qw ( TriggerHook );
use DE_EPAGES::Core::API::Log qw (LogDebug GetLog);
use DE_EPAGES::Object::API::Factory
    qw( LoadObject ExistsObjectByPath LoadObjectByPath Transaction DeleteObject LoadClassByAlias);
use DE_EPAGES::Order::API::LineItemContainer qw(SaveShipping);
use DE_EPAGES::Object::API::Object::Object qw(clone insertChild);
use Data::Dumper;
use Options::UserSync::API::CountriesConverter;

#This library covers method called from OrderPlace.pm and OrderUpdate.pm
#WARNING! - Before change - test compatibility.

sub getShippingAddress {
    my ( $Order, $alreadyPreparedPart ) = @_;
    return _getAddress( $Order, $alreadyPreparedPart, 'shipping' );
}

sub getBillingAddress {
    my ( $Order, $alreadyPreparedPart ) = @_;
    return _getAddress( $Order, $alreadyPreparedPart, 'billing' );
}

sub _getAddress {
    my ( $Order, $alreadyPreparedPart, $type ) = @_;
    if ( $type eq 'billing' ) {
        return _getAddressDetails( $Order->get('BillingAddress'),
            $alreadyPreparedPart, '' );
    }
    elsif ( $type eq 'shipping' ) {
        my $ShippingAddress = $Order->get('ShippingAddress');
        if ( defined($ShippingAddress) && $ShippingAddress ) {
            return _getAddressDetails( $ShippingAddress, $alreadyPreparedPart,
                'AA_' );
        }
        else {
            my $BillingAddress = $Order->get('BillingAddress');
            return _getAddressDetails( $BillingAddress, $alreadyPreparedPart,
                'AA_' );
        }
    }
}

sub _getAddressDetails {
    my ( $Address, $alreadyPreparedPart, $pref ) = @_;
    my $AddressFields = {
        'AddressExtension' => 'Address1',
        'Street'           => 'Address2',
        'Street2'          => 'Address3',
        'AddressNumber'    => 'AddressNumber',
        'Country'          => 'Country',         #extract the HASH
        'EMail'            => 'Email',
        'FirstName'        => 'FirstName',
        'LastName'         => 'Surname',
        'Phone'            => 'DayPhone',
        'Salutation'       => 'Salutation',
        'State'            => 'County',
        'Title'            => 'TitleCode',
        'Zipcode'          => 'Postcode',
        'City'             => 'Town',
        'Salutation'       => 'Salutation',
        'ModifiedOn'       => 'ModifiedOn',
        'Company'          => 'AddressRef1',
        'Department'       => 'AddressRef2'
    };
    while ( my ( $valEpages, $valOptions ) = each(%$AddressFields) ) {
        if ( $valEpages eq 'Country' ) {
            $alreadyPreparedPart->{ $pref . $valOptions }
                = _getCountryCode3($Address);
        }
        elsif ( $valEpages eq 'ModifiedOn' ) {
            $alreadyPreparedPart->{ $pref . $valOptions }
                = "2011-01-14T00:00:00";
        }
        elsif ( $valEpages eq 'AddressNumber' ) {
            if ( defined $Address->get($valEpages) ) {
                $alreadyPreparedPart->{ $pref . $valOptions }
                    = $Address->get($valEpages);
            }
            else {
                $alreadyPreparedPart->{ $pref . $valOptions } = 0;
            }
        }
        else {
            if ( defined $Address->get($valEpages) ) {
                $alreadyPreparedPart->{ $pref . $valOptions }
                    = $Address->get($valEpages);
            }
            else {
                $alreadyPreparedPart->{ $pref . $valOptions } = "";
            }
        }
    }
    return $alreadyPreparedPart;
}

sub getCreditCardDetails {
    my ($LineItemContainer) = @_;
    my $linePayment         = $LineItemContainer->get('Payment');
    my $basketID            = "";
    my $month               = "";
    my $year                = "";

    if ( defined($linePayment) ) {
        GetLog->error( '****' . $linePayment->get('Class')->get('Alias') );
        if ( $linePayment->get('Class')->get('Alias') ne
            'LineItemPaymentDataCash' )
        {
            $linePayment = undef;
        }
        else {
            $basketID
                = $LineItemContainer->get('Parent')->get('Parent')->get('ID');
            $month = substr $linePayment->get('DC_Expiry'), 0, 2;
            $year = substr $linePayment->get('DC_Expiry'), -2;
        }
    }
    else {
        $linePayment = undef;
    }

    my $orderToValidate = {
        'CCNumber' => ( defined($linePayment) )
        ? ( ( $linePayment->get('DC_PAN') )
            ? $linePayment->get('DC_PAN')
            : 0
            )
        : 0,
        'CCExpiryMonth' => ( defined($linePayment) )
        ? ( ($month)
            ? $month
            : 0
            )
        : 0,
        'CCExpiryYear' => ( defined($linePayment) )
        ? ( ($year)
            ? $year
            : 0
            )
        : 0,
        'CCAuthCode' => ( defined($linePayment) )
        ? ( ( $linePayment->get('DC_AuthCode') )
            ? $linePayment->get('DC_AuthCode')
            : 0
            )
        : 0,
        'CCReceiptNumber' => ( defined($linePayment) )
        ? ( ( $linePayment->get('DC_Info') )
            ? $linePayment->get('DC_Info')
            : 0
            )
        : 0,
        'CCTransactionCode' => ( defined($linePayment) )
        ? ( ( $linePayment->get('DC_Reference') )
            ? $linePayment->get('DC_Reference')
            : 0
            )
        : 0,
        'CCStartYear'  => '0',
        'CCStartMonth' => '0',
        'CCCv2'        => '0',
        'CCType'       => ( defined($linePayment) )
        ? ( ( $linePayment->get('DC_CardScheme') )
            ? $linePayment->get('DC_CardScheme')
            : 0
            )
        : 0,
        'CCIssueNumber' => '0',
    };
    return $orderToValidate;
}

sub getCreditCardDetails_LineItemPaymentDCC_ForValidation_x {
    my ($LineItemContainer) = @_;
    my $orderToValidate = {
        'CCType'            => '',
        'CCNumber'          => '0',
        'CCCv2'             => '0',
        'CCExpiryMonth'     => '0',
        'CCExpiryYear'      => '0',
        'CCIssueNumber'     => '0',
        'CCStartMonth'      => '0',
        'CCStartYear'       => '0',
        'CCAuthCode'        => '',
        'CCTransactionCode' => '',
        'CCReceiptNumber'   => '',
    };
    return $orderToValidate;
}

sub getCreditCardDetails_LineItemPaymentDCC_ForValidation {
    my ($LineItemContainer) = @_;
    my $linePayment = $LineItemContainer->get('Payment');
    if ( defined($linePayment) ) {
        if ($linePayment->get('Class')->get('Alias') ne 'LineItemPaymentDCC' )
        {
            $linePayment = undef;
        }
    }
    else {
        $linePayment = undef;
    }
    my $orderToValidate = {
        'CCType' => ( defined($linePayment) )
        ? ( ( $linePayment->get('CreditCardType') )
            ? $linePayment->get('CreditCardType')
            : 0
            )
        : 0,
        'CCNumber' => ( defined($linePayment) )
        ? ( ("$linePayment->get('CreditCardNumber')")
            ? $linePayment->get('CreditCardNumber')
            : 0
            )
        : 0,
        'CCCv2' => ( defined($linePayment) )
        ? ( ( $linePayment->get('CVV') ) ? $linePayment->get('CVV') : 0 )
        : 0,
        'CCExpiryMonth' => ( defined($linePayment) )
        ? ( ( $linePayment->get('ValidThruMonth') )
            ? $linePayment->get('ValidThruMonth')
            : 0
            )
        : 0,
        'CCExpiryYear' => ( defined($linePayment) )
        ? ( ( $linePayment->get('ValidThruYear') )
            ? $linePayment->get('ValidThruYear')
            : 0
            )
        : 0,
        'CCIssueNumber' => ( defined($linePayment) )
        ? ( ( $linePayment->get('IssueNumber') )
            ? $linePayment->get('IssueNumber')
            : 0
            )
        : 0,
        'CCStartMonth' => ( defined($linePayment) )
        ? ( ( $linePayment->get('ValidFromMonth') )
            ? $linePayment->get('ValidFromMonth')
            : 0
            )
        : 0,
        'CCStartYear' => ( defined($linePayment) )
        ? ( ( $linePayment->get('ValidFromYear') )
            ? $linePayment->get('ValidFromYear')
            : 0
            )
        : 0,
        'CCAuthCode'        => '',
        'CCTransactionCode' => '',
        'CCReceiptNumber'   => '',
    };
    return $orderToValidate;
}

sub _getCountryCode3 {
    my ($Address) = @_;

    my $Country = $Address->get('CountryID');
    return $Country;
}

sub addCountryCode {
    my ( $Order, $alreadyPreparedPart ) = @_;
    my $BillingAddress = $Order->get('BillingAddress');
    $alreadyPreparedPart->{'CountryCode'} = _getCountryCode3($BillingAddress);
    return $alreadyPreparedPart;
}

sub addLineItems {
    my ( $LineItemContainer, $alreadyPreparedPart ) = @_;
    my ( $itemsArray, $BasketLineItemsCounter )
        = addLineItemsToFinalOrder($LineItemContainer);
    $alreadyPreparedPart->{'OrderLine'} = $itemsArray;
    return $alreadyPreparedPart;
}

sub addLineItemsToFinalOrder {
    my ($LineItemContainer) = @_;
    my $lineItems = $LineItemContainer->get('LineItems');
    my @itemsArray;
    my $BasketLineItemsCounter = 0;
    foreach (@$lineItems) {
        if ( $_->get('Class')->get('Alias') ne "LineItemProductUpdate" ) {
            my $IsPromotion = 'false';
            if ( $_->get('IsLineItemOptionsBonus') ) {
                $IsPromotion = 'true';
            }

            my %item = (
                'ProductCode' => $_->get('SKU'),
                'Quantity'    => $_->get('Quantity'),
                'Price'       => $_->get('LineItemPriceFromOptions'),
                'PricePer'    => 1,
                'IsPromotion' => $IsPromotion,
                'SourceKey'   => 'WEB1BIB',
            );
            push( @itemsArray, {%item} );
            $BasketLineItemsCounter++;
        }
    }
    return ( \@itemsArray, $BasketLineItemsCounter );
}

sub addLineItemsToFinalOrderOOOLD {
    my ($LineItemContainer) = @_;
    my $lineItems = $LineItemContainer->get('LineItems');
    my @itemsArray;
    my $BasketLineItemsCounter = 0;
    foreach (@$lineItems) {
        if ( $_->get('Class')->get('Alias') ne "LineItemProductUpdate"
            && !$_->get('IsLineItemOptionsBonus') )
        {
            my %item = (
                'ProductCode' => $_->get('SKU'),
                'Quantity'    => $_->get('Quantity'),
                'Price'       => $_->get('LineItemPriceFromOptions'),
                'PricePer'    => 1,
                'SourceKey'   => 'WEB1BIB',
            );
            push( @itemsArray, {%item} );
            $BasketLineItemsCounter++;
        }
    }
    return ( \@itemsArray, $BasketLineItemsCounter );
}

sub addLineItemsToValidateRequest {
    my ($LineItemContainer) = @_;
    my $lineItems = $LineItemContainer->get('LineItems');
    my @itemsArray;
    my $BasketLineItemsCounter = 0;
    foreach (@$lineItems) {
        if ( $_->get('Class')->get('Alias') ne "LineItemProductUpdate"
            && !$_->get('IsLineItemOptionsBonus') )
        {
            my %item = (
                'ProductCode' => $_->get('SKU'),
                'Quantity'    => $_->get('Quantity'),
                'Price'       => $_->get('LineItemPrice'),
                'PricePer'    => 1,
                'SourceKey'   => 'WEB1BIB',
            );
            push( @itemsArray, {%item} );
            $BasketLineItemsCounter++;
        }
    }
    return ( \@itemsArray, $BasketLineItemsCounter );
}

sub addShippingPrice {
    my ( $Order, $alreadyPreparedPart ) = @_;
    my $LineItemContainer = $Order->get('LineItemContainer');
    GetLog->debug( "Shipping Price TEST: "
            . $LineItemContainer->get('Shipping')->get('LineItemPrice') );
    $alreadyPreparedPart->{'ShippingCost'}
        = $LineItemContainer->get('Shipping')->get('LineItemPrice');
    return $alreadyPreparedPart;
}

1;
